<?php

namespace tmcore\utils;

/**
 * Aes 加密类
 * @package tmcore\utils
 */
class Aes
{
    /**
     * 密钥
     * @var string
     */
    protected $key = '';

    /**
     * 偏移量
     * @var string
     */
    protected $iv = '';

    /**
     * 加密方式
     * @var string
     */
    protected $method = '';

    /**
     * Aes constructor.
     * @param string $key 盐值
     * @param string $iv 偏移量
     * @param string $method 加密方式
     */
    public function __construct(string $key, string $iv, string $method = 'AES-256-CBC')
    {
        $this->key = $key;
        $this->iv = $iv;
        $this->method = $method;
    }

    /**
     * aes加密
     * @param string $data
     * @return string
     */
    public function encrypt($data): string
    {
        return base64_encode(openssl_encrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv));
    }

    /**
     * aes解密
     * @param $data
     * @return array|false|mixed|string
     */
    public function decrypt($data)
    {
        return openssl_decrypt(base64_decode($data), $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
    }
}